package main

import (
	"context"
	"embed"
	"kafka-ui/backend/common"
	"kafka-ui/backend/config"
	"kafka-ui/backend/log"
	"kafka-ui/backend/service"
	"time"

	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/options/linux"
	"github.com/wailsapp/wails/v2/pkg/options/windows"
)

//go:embed all:frontend/dist
var assets embed.FS

func main() {
	// Create an instance of the app structure
	cancelCtx, cancel := context.WithCancel(context.Background())
	app := NewApp()
	appConfig := &config.AppConfig{}

	log := log.NewLogger(appConfig.GetDirPath())
	log.Info("日志打印")
	kafkaService := service.NewKafkaService(log)
	go func() {
		select {
		case <-cancelCtx.Done():
			log.Close()
			kafkaService.Close(cancelCtx)
		default:
			time.Sleep(10 * time.Second)
		}
	}()
	// Create application with options
	err := wails.Run(&options.App{
		Title:     common.AppName,
		Width:     common.Width,
		Height:    common.Height,
		Frameless: true, // 无边框
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		OnStartup: func(ctx context.Context) {
			app.Start(ctx)
			log.Info("启动开始")
		},
		// 在前端加载完毕 index.html 及其资源后调用此回调
		OnDomReady: app.domReady,

		//在前端被销毁之后，应用程序终止之前，调用此回调。 它提供了应用程序上下文。
		OnBeforeClose: func(ctx context.Context) (prevent bool) {
			kafkaService.Close(ctx)
			log.Close()
			log.Info("应用程序即将关闭")
			cancel()
			return
		},
		//应用关闭前回调
		OnShutdown: func(ctx context.Context) {},
		Windows: &windows.Options{
			ResizeDebounceMS: 2,
		},
		Linux: &linux.Options{
			ProgramName: "kafka-ui",
		},
		Bind: []interface{}{
			app,
			appConfig,
			kafkaService,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}
